import React, { Component } from 'react';

import {NavBar} from 'antd-mobile'
import "../styles/Reg.css"

import {register} from "../api/index"
class MyReg extends Component {
    constructor(props){
        super(props);
        this.state={
            phone:'',
            pass:'',
            pass2:'',
            xuan:''
        }
    }
    back(){
        this.props.history.goBack()
    }
    lose(){
        register({phone:this.state.phone,pass:this.state.pass}).then((res)=>{
            console.log(res);
            if(res.data.code==400){ // eslint-disable-line
                alert("该账号已经注册过了!!!请重新注册")
            }
        })
    }
    handleChange(e){
        // setState异步的
        this.setState({
            [e.target.name]:e.target.type=='checkbox'?e.target.checked:e.target.value, // eslint-disable-line
        },()=>{
        // console.log(this.state.phone,"里");
        })
        // console.log(this.state.phone,"外");
    }
    logging(){
        // 要是电话号码和密码都不为空的话就发送请求
        if(
            this.state.phone != "" && // eslint-disable-line
            this.state.pass != "" && // eslint-disable-line
            this.state.pass2 != "" // eslint-disable-line
        ){
            if (this.state.pass!=this.state.pass2) { // eslint-disable-line
                alert("两次输入的密码不一致，请重新输入！")
                this.setState({pass2:""})
            }
            if(this.state.pass==this.state.pass2){ // eslint-disable-line
                register({phone:this.state.phone,pass:this.state.pass}).then((res)=>{
                    console.log(res);
                    alert("注册成功")
                    this.props.history.push("/login")
                })
            }
        }
    }
    render() {
        return (
            <div className='register'>
                {/* <h2>注册</h2> */}
                <NavBar onBack={()=>{ this.back() }}>注册</NavBar>
                {/* 表单元素的值不受当前组件状态控制===========不受控组件 */}
                <input name='phone' type="text" placeholder='输入电话号码' value={this.state.phone} onChange={(e)=>{this.handleChange(e)}}/>
                <br />
                {/* 受控组件 : 值受到 React 组件状态控制的表单元素 */}
                {/* 一般是通过 defaultValue 属性, onChange 事件配合将非受控组件变为受控组件. */}
                <input name='pass' type="text" placeholder='输入密码' value={this.state.pass} onChange={(e)=>{this.handleChange(e)}}  onBlur={()=>{this.lose()}}/>
                <br />
                <input name='pass2' type="text" placeholder='确认密码' value={this.state.pass2} onChange={(e)=>{this.handleChange(e)}}/>
                <br />
                <div className="fuxuan">
                    <input name='xuan' type="checkbox" />勾选用户登录协议
                </div>
                <br />
                <button onClick={()=>{this.logging()}}>注册</button>
            </div>
        );
    }
}

export default MyReg;
